
import 'package:flutter/material.dart';

class YkNavigationTabModel {

  final String name;

  double? height;

  YkNavigationTabModel({required this.name, this.height});
}

class YkNavigationTabConfigModel {

  TextStyle? selectTextStyle;

  TextStyle? unSelectTextStyle;

  Color? indicatorColor;

  double? indicatorWeight;

  Color? dividerColor;

  double? dividerHeight;

  Function(int)? onPageSelected;

  Future<void> Function(int)? _updateIndex;

  YkNavigationTabConfigModel({this.selectTextStyle, this.unSelectTextStyle, this.indicatorColor, this.dividerColor, this.dividerHeight, this.indicatorWeight, this.onPageSelected});

  Future<void> updateIndex(int index) {
    return _updateIndex?.call(index) ?? Future.value();
  }
}

class YkNavigationWidget extends StatefulWidget {

  final List<YkNavigationTabModel> widgets;

  final List<Widget> pages;

  YkNavigationTabConfigModel? configModel;

  YkNavigationWidget({super.key, required this.widgets, required this.pages, this.configModel});

  @override
  State<YkNavigationWidget> createState() => _YkNavigationWidgetState();
}

class _YkNavigationWidgetState extends State<YkNavigationWidget> with SingleTickerProviderStateMixin {

  TabController? tabController;
  int _currentIndex = 0;

  @override
  void initState() {

    tabController = TabController(length: widget.widgets.length, vsync: this);

    widget.configModel?._updateIndex = (index) async {
      return tabController?.animateTo(index, duration: const Duration(milliseconds: 500));
    };

    tabController?.addListener(() {
      if (tabController != null) {
        if (_currentIndex != tabController!.index) {
          widget.configModel?.onPageSelected?.call(tabController!.index);
        }
        _currentIndex = tabController!.index;
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    tabController?.dispose();
    tabController = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: widget.widgets.length,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TabBar(
            labelStyle: widget.configModel?.selectTextStyle,
            unselectedLabelStyle: widget.configModel?.unSelectTextStyle,
            indicatorColor: widget.configModel?.indicatorColor,
            indicatorWeight: widget.configModel?.indicatorWeight ?? 2.0,
            dividerColor: widget.configModel?.dividerColor,
            dividerHeight: widget.configModel?.dividerHeight,
            tabs: widget.widgets.map((item) {
              return Tab(text: item.name, height: item.height,);
            }).toList(),
            controller: tabController,
          ),
          Expanded(
            child: TabBarView(
              controller: tabController,
              children: widget.pages,
            ),
          )
        ],
      ),
    );
  }
}

